package com.rorochen.server.gotty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * 快速启动简易netty服务器
 * @author chenqi
 * @date 2021-12-08 11:11
 */
public class GottyServerBootstrap {

    private ServerSocketChannel server;

    private EventLoopGroup eventLoopGroup;

    private Selector reactor;


    public GottyServerBootstrap() throws IOException {
        this.server =  ServerSocketChannel.open();
        server.socket().bind(new InetSocketAddress(1080));
        server.configureBlocking(false);
        reactor=Selector.open();
    }



    public void setBootStrap(EventLoopGroup eventLoopGroup) throws IOException {
        this.eventLoopGroup=eventLoopGroup;
    }


    public void start() throws ClosedChannelException {
        this.server.register(reactor, SelectionKey.OP_ACCEPT);
        this.eventLoopGroup.start();
        for(;;){
            try{
                int r=this.reactor.select();
                if( r > 0 ){
                    Iterator<SelectionKey> it = this.reactor.selectedKeys().iterator();
                    while(it.hasNext()) {
                        SelectionKey keyn = it.next();
                        it.remove();
                        if(keyn.isAcceptable() && keyn.isValid() ){
                            ServerSocketChannel ssc = (ServerSocketChannel) keyn.channel();
                            SocketChannel clientChannel = ssc.accept();
                            clientChannel.socket().setSoTimeout(3000);
                            clientChannel.configureBlocking(false);
                            eventLoopGroup.register(clientChannel);
                            System.out.println("新增连接："+clientChannel.getRemoteAddress());

                        }


                    }


                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }



    }
}
